package com.heima.wemedia.config;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.WmThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义的springmvc拦截器
 */
public class WebMvcInterceptor implements HandlerInterceptor {
    /**
     * 目的方法执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("token");
        //解析token
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        Integer userId = (Integer) claimsBody.get("id");
        //封装到thread Local中
        WmUser wmUser = new WmUser();
        wmUser.setId(userId);
        WmThreadLocal.setWmUser(wmUser);
        //放行
        return true;
    }

    /**
     * 目的方法执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        WmThreadLocal.removeWmUser();
    }
}
